<?php
namespace Api\Model;

use Think\Model;

class WaterPurifierModel extends ApiBaseModel
{

    public function checkReceive($userId)
    {
        $order = M('WaterPurifierOrder');
        $map['user_id'] = $userId;
        $map['order_type'] = 1;
        $map['is_deleted'] = 0;
        $map['order_status'] = 1;
        $map['pay_time'] = array('gt',0);
        $orderInfo = $order->where($map)->find();
        if ($orderInfo) {
            return $orderInfo['brand'];
        }else{
            return false;
        }
    }

    //获取净水器介绍
    public function getIntroduce($brand = 1)
    {
        $map['brand'] = $brand;
        $map['config_key'] = array('LIKE', 'introduce_pic%');
        $map['is_deleted'] = 0;
        $map['status'] = 1;
        $introduce = $this->field('url')->where($map)->order('config_key asc')->select();
        return $introduce;
    }

    public function getReceiveInfo($registerTime, $brand)
    {
        $map['config_key'] = array('LIKE', 'receive_%');
        $map['is_deleted'] = 0;
        $map['status'] = 1;
        $map['brand'] = $brand;
        $receive = $this->where($map)->select();
        if (!$receive) {
            return false;
        }
        //$data['total'] = 0;
        $data = array();
        foreach ($receive as $k => $v) {
            if(strpos($v['config_key'], 'actually_price')){
                $data['actually_price'] = $v['price'];
                $data['name'] = $v['config_value'];
            }elseif (strpos($v['config_key'], 'activity_price')){
                $data['activity_price'] = $v['price'];
            //    $data['total'] += $v['price'];
            }elseif (strpos($v['config_key'], 'deliver_price')) {
                $data['deliver_price'] = $v['price'];
                $data['deliver_name'] = $v['config_value'];
            //    $data['total'] += $v['price'];
            }elseif (strpos($v['config_key'],'install_price')) {
                $data['install_price'] = $v['price'];
                $data['install_name'] = $v['config_value'];
            //    $data['total'] += $v['price'];
            }elseif (strpos($v['config_key'], 'activity_day')){
                $data['activity_day'] = $v['day'];
            }elseif (strpos($v['config_key'], 'description')){
                $data['description'] = $v['config_value'];
            }
        }
        //计算用户免费剩余时间
        $second = $data['activity_day'] * 86400 - (time() - $registerTime);
        if ($second > 0) {
            $data['day'] = ceil($second / 86400);
        }else{
            $data['day'] = 0;
        }
        return $data;
    }
    
    //净水器更换项目与收费
    public function getReplaceInfo($userId, $brand)
    {
        //获取净水器领取更换记录
        $order = M('WaterPurifierOrder');
        $map['user_id'] = $userId;
        $map['order_type'] = 1; //1领取2更换
        $map['finish_time'] = array('gt', 0);
        $map['is_deleted'] = 0;
        $receiveLog = $order->field('finish_time')->where($map)->order('finish_time')->find();
        $map['order_type'] = 2;
        $replaceLog = $order->field('finish_time')->where($map)->order('finish_time desc')->find();
        $log = array();
        $log[0]['time'] = date('Y年m月d日 H:i:s', $receiveLog['finish_time']);
        $log[0]['content'] = '领取了净水器';
        if ($replaceLog) {
            $lastTime = $replaceLog['finish_time'];
            $log[1]['time'] = date('Y年m月d日 H:i:s', $replaceLog['finish_time']);
            $log[1]['content'] = '更换了滤芯';
        }else{
            $lastTime = $receiveLog['finish_time'];
        }
        
        unset($map);
        $map['config_key'] = 'replace_suggest_day';
        $map['brand'] = $brand;
        $day = M('WaterPurifier')->where($map)->getField('day');
        $day or $day = 90;

        //计算是否需要提示
        if((time() - $lastTime) > $day * 86400){ //如果领取更换超过90天就提示
            $notice = '温馨提示：你已经连续'.$day.'天没有换滤芯了，为了你和家人的喝水健康，请及时更换滤芯。';
        }else{
            $notice = '';
        }
        unset($map);

        //查找可更换项目
        $item = $this->getItem('replace', $brand);
        $data['log'] = $log;
        $data['replace'] = $item;
        $data['notice'] = $notice;
        return $data;
    }

    //净水器更换项目与收费
    public function getRepairInfo($brand)
    {
        //查找可更换项目
        $item = $this->getItem('repair', $brand);
        return $item;
    }

    public function getItem($key, $brand)
    {
        $map['config_key'] = array('LIKE', $key.'%');
        $map['status'] = 1;
        $map['is_deleted'] = 0;
        $map['brand'] = $brand;
        $res = $this->where($map)->order('config_key')->select();
        if (!$res) {
            $res = array();
        }
        $item = array();
        foreach (@$res as $k => $v) {
            if (strpos($v['config_key'], 'item') === false) {
                if(strpos($v['config_key'], 'price')){
                    $item['service']['name'] = $v['config_value'];
                    $item['service']['price'] = $v['price'];
                    $item['service']['key'] = $v['config_key'];
                }
            }else{
                $item['item'][] = array('name' => $v['config_value'],
                                        'price' => $v['price'],
                                        'key' => $v['config_key']);
            }
        }
        return $item;
    }

    //服务记录
    public function getServiceRecord($userId)
    {
        $model = M('WaterPurifierOrder');
        $map['user_id'] = $userId;
        $map['status'] = 1;
        $map['is_deleted'] = 0;
        $map['finish_time'] = array('gt', 0);

        $res = $model->field('order_id,finish_time,order_type')
             ->where($map)->order('finish_time')->select();

        foreach ($res as $k => $v) {
            $res[$k]['time'] = date('Y年m月d日 H:i:s', $v['finish_time']);
            $content = '';
            if($v['order_type'] == 1){
                $content = '领取了净水器';
            }elseif($v['order_type'] == 2){
                $content = '更换了滤芯';
            }else{
                $content = '进行了维修';
            }
            $res[$k]['content'] = $content;
        }
        return $res;
    }

    public function doOrder($userId, $registerTime)
    {
        $addrId = I('post.address_id', 0, 'intval');
        $paymentCode = I('post.payment_code', 0, 'intval');
        $orderType = I('post.order_type', 0, 'intval');
        $brand = I('post.brand', 1, 'intval');

        if (!in_array($brand, array(1, 2, 3))) {
            $this->setError(10001, '净水器品牌错误');
            return false;
        }
        $addr = M('address');
        $map['id'] = $addrId;
        $map['user_id'] = $userId;
        $address = $addr->where($map)->find();
        if (!$address) {
            $this->setError(20001, '安装地址错误');
            return false;
        }
        if (!in_array($paymentCode, array(1,2,3))) {
            $this->setError(10001, '支付方式错误');
            return false;
        }

        if (!in_array($orderType, array(1,2,3))) {
            $this->setError(10001, '订单类型错误');
            return false;
        }
        //组装订单数据
        $order = array();
        $order['user_id'] = $userId;
        $order['shipping_tel'] = $address['phone'];
        $order['shipping_name'] = $address['contacts'];
        $order['shipping_addr'] = $address['address'];
        $order['doorplate'] = $address['doorplate'];
        $order['city'] = $address['city'];
        $order['province'] = $address['province'];
        $order['lng'] = $address['lng'];
        $order['lat'] = $address['lat'];
        $order['order_type'] = $orderType;
        $order['payment_code'] = $paymentCode;
        $order['add_time'] = time();
        $order['total'] = 0;
        $order['reduce'] = 0;
        $order['order_num'] = build_order_no();
        $order['ip'] = $_SERVER['REMOTE_ADDR'];
        $order['brand'] = $brand;

        if ($orderType == 1) { //领取订单
            $res = $this->receiveOrder($order, $registerTime);
        }else{ //维修更换订单
            $res = $this->replaceOrRepairOrder($order);
        }
        return $res;
    }


    /**
     * 领取净水器下单操作
     * @param  array $orrder      订单信息
     * @param  int $registerTime 用户注册时间
     * @return mixed               
     */
    public function receiveOrder($order, $registerTime = 0)
    {
        //to do 限制下单数量
        $orderModel = M('WaterPurifierOrder');
        $detailModel = M('WaterPurifierOrderDetail');

        $map['order_type'] = 1;
        $map['user_id'] = $order['user_id'];
        $map['order_status'] = 1;
        $count = $orderModel->where($map)->count();
        if ($count) {
            $this->setError(20001, '每位用户只能领取一次净水器');
            return false;
        }
        if (intval($registerTime) <= 0) {
            $this->setError(10001, '用户注册时间获取失败');
            return false;
        }
        //领取配置数据
        unset($map);
        $purifier = M('WaterPurifier');
        $map['config_key'] = 'receive_activity_day';
        $map['brand'] = $order['brand'];
        $activityDay = $purifier->where($map)->getField('day');
        unset($map);
        $map['config_key'][] = array('LIKE', 'receive%');
        $map['config_key'][] = array('LIKE', '%price');
        $map['brand'] = $order['brand'];
        $price = $purifier->where($map)->select();
        if (!$price) {
            $this->setError(20001, '净水器品牌错误');
            return false;
        }
        $orderDetail = array();
        $detail = array();
        $second = $activityDay * 86400 - (time() - $registerTime);
       
         //组装订单详情数组
        foreach ($price as $v) {
            $detail['item_key'] = $v['config_key'];
            $detail['item_name'] = $v['config_value'];
            $detail['user_id'] = $order['user_id'];
            $detail['order_type'] = $order['order_type'];
            $detail['price'] = $v['price'];
            $detail['add_time'] = time();
            $detail['reduce'] = 0;
            $orderDetail[] = $detail;
        }

        //净水器实际价格
        $priceMap['config_key'] = 'receive_actually_price';
        $priceMap['brand'] = $order['brand'];
        $realPrice = $purifier->where($priceMap)->getField('price');

        //计算订单支付金额和减免金额
        foreach ($orderDetail as $k => $v) {
            if($second > 0 and $v['item_key'] == 'receive_activity_price'){
                $orderDetail[$k]['reduce'] = $realPrice - $v['price'];
                $order['reduce'] = $realPrice - $v['price'];
            }
            if ($second <= 0 and $v['item_key'] == 'receive_activity_price') {
                unset($orderDetail[$k]);
            }
            if($v['item_key'] != 'receive_activity_price'){
                $order['total'] += $v['price'];
            }
        }
        $orderDetail = array_merge($orderDetail);
        $order['actually_total'] = $order['total'] - $order['reduce'];

        //var_dump($orderDetail);exit;
        //插入订单数据
        $orderModel->startTrans();
        $orderId = $orderModel->add($order);
        if ($orderId) {
            foreach ($orderDetail as $k => $v) {
                $orderDetail[$k]['order_id'] = $orderId;
            }
            $res = $detailModel->addAll($orderDetail, array(), true);
            if ($res) {
                $orderModel->commit();
                return true;
            }else{
                $orderModel->rollback();
                $this->setError(50000, '下单失败');
                return false;
            }
        }else{
            $orderModel->rollback();
            $this->setError(50000, '下单失败');
            return false;
        }
    }

    public function replaceOrRepairOrder($order)
    {
        $orderModel = M('WaterPurifierOrder');
        $detailModel = M('WaterPurifierOrderDetail');

        $map['order_type'] = $order['order_type'];
        $map['user_id'] = $order['user_id'];
        $map['order_status'] = 1;
        $map['finish_time'] = 0;
        $count = $orderModel->where($map)->count();
        if ($count) {
            $this->setError(20001, '您有未完成的订单，请稍后再操作');
            return false;
        }
        //更换配置数据
        $items = I('post.items', array());
        $purifier = M('WaterPurifier');
        if (!is_array($items) or empty($items)) {
            $this->setError(10001, '更换或维修项目不能为空');
        }

        $orderDetail = array();
        $detail = array();
        foreach ($items as $k => $v) {
            unset($map);
            $map['config_key'][] = array('eq', $v);
            $map['status'] = 1;
            $map['is_deleted'] = 0;
            $map['brand'] = $order['brand'];
            if($order['order_type'] == 2){
                $map['config_key'][] = array('LIKE', 'replace%');
            }else{
                $map['config_key'][] = array('LIKE', 'repair%');
            }
            $config = $purifier->where($map)->find();
            if (!$config) {
                $this->setError(10001, '更换或维修项目错误');
                return false;
            }
            $detail['item_key'] = $config['config_key'];
            $detail['item_name'] = $config['config_value'];
            $detail['user_id'] = $order['user_id'];
            $detail['order_type'] = $order['order_type'];
            $detail['price'] = $config['price'];
            $detail['add_time'] = time();
            $detail['reduce'] = 0;
            $orderDetail[] = $detail;

            $order['total'] += $config['price'];
        }

        $order['actually_total'] = $order['total'];
       
        //插入订单数据
        $orderModel->startTrans();
        $orderId = $orderModel->add($order);
        if ($orderId) {
            foreach ($orderDetail as $k => $v) {
                $orderDetail[$k]['order_id'] = $orderId;
            }
            $res = $detailModel->addAll($orderDetail, array(), true);
            if ($res) {
                $orderModel->commit();
                return true;
            }else{
                $orderModel->rollback();
                $this->setError(50000, '下单失败');
                return false;
            }
        }else{
            $orderModel->rollback();
            $this->setError(50000, '下单失败');
            return false;
        }
    }

    public function getOrderInfo($userId, $orderId)
    {
        $orderModel = M('WaterPurifierOrder');
        $map['user_id'] = $userId;
        $map['is_deleted'] = 0;
        if(mb_strlen($orderId) == 20){
            $map['order_num'] = $orderId;
        }else{
            $map['order_id'] = $orderId;
        }

        $order = $orderModel->where($map)->find();

        if (!$order) {
            $this->setError(20001, '订单不存在');
            return false;
        }
        $data = array();
        //订单号、地址、服务电话
        $data['order_num'] = $order['order_num'];
        $data['shipping_addr'] = $order['shipping_addr'].$order['doorplate'];
        $telMap['config_key'] = 'introduce_tel';
        $telMap['brand'] = $order['brand'];
        $tel = M('WaterPurifier')->where($telMap)->getField('url');
        $tel or $tel = '暂无';
        $data['service_tel'] = $tel;
        //服务项目 
        if($order['order_type'] == 1){
            $name = '净水器－领取安装';
        }elseif($order['order_type'] == 2){
            $name = '净水器－更换滤芯';
        }else{
            $name = '净水器－维修';
        }
        $data['service_name'] = $name;
        //服务状态与订单状态
        if($order['finish_time'] > 0){
            $data['service_status'] = 1;
            $data['service_status_text'] = '服务完成';
            // $data['log']['time'] = date('Y年m月d日 H:i', $order['finish_time']);
            // $data['log']['title'] = '订单已完成';
            // $data['log']['content'] = '净水器已安装完成';
        }else{
            $data['service_status'] = 0;
            $data['service_status_text'] = '服务中';
            // $data['log']['time'] = date('Y年m月d日 H:i', $order['add_time']);
            // $data['log']['title'] = '订单提交成功';
            // $data['log']['content'] = '客服将会在72小时内联系您，指派师傅上门安装';
        }
        if ($order['cancel_time'] > 0) {
            $data['service_status'] = 2;
            $data['service_status_text'] = '已取消';
        }
        //支付状态
        if ($order['pay_time'] > 0) {
            $data['payment_status'] = '已支付';
            $payModel = M('UserPayRecord');
            $payMap['order_id'] = $order['order_num'];
            $payRecord = $payModel->where($payMap)->find();
            if ($payRecord and $payRecord['channel'] != 'offline') {
                $data['payment_type'] = '在线支付';
            }else{
                $data['payment_type'] = '线下支付';
            }
        }else{
            $data['payment_status'] = '未支付';
            $data['payment_type'] = '暂无';
        }
        //支付总额
        $data['amount'] = '￥'.$order['actually_total'];
        //净水器订单详情
        $detailModel = M('WaterPurifierOrderDetail');
        unset($map);
        $map['order_id'] = $order['order_id'];
        $map['is_deleted'] = 0;
        $map['reduce'] = 0;
        $detail = $detailModel->field('item_name,item_key,price')
                ->where($map)->order('item_key asc')->select();
        if ($order['order_type'] == 1 and $order['reduce'] > 0) {
            foreach ($detail as $k => $v) {
                if($v['item_key'] == 'receive_actually_price'){
                    $price = $v['price'] - $order['reduce'];
                    $price = number_format($price, 2, '.', '');
                    $detail[$k]['price'] = '￥'.$price.' (￥'.$v['price'].')';
                }else{
                    $detail[$k]['price'] = '￥'.$v['price'];
                }
                unset($detail[$k]['item_key']);
            }
        }
        $data['detail'] = $detail;
        return $data;

    }

    // public function orderStatus($userId, $orderId)
    // {
    //     $orderModel = M('WaterPurifierOrder');
    //     $map['user_id'] = $userId;
    //     $map['order_id'] = $orderId;

    //     $order = $orderModel->where($map)->find();
    //     if (!$order) {
    //         $this->setError(20001, '订单不存在');
    //         return false;
    //     }
    //     $status = array();
    //     if($order['finish_time'] > 0){
    //         $data['title'] = '安装完成';
    //         $data['time'] = date('Y-m-d H:i:s', $order['finish_time']);
    //         $data['content'] = '净水器已安装完成';
    //         $status[] = $data;
    //     }
    //     $data['title'] = '订单提交成功';
    //     $data['time'] = date('Y-m-d H:i:s', $order['add_time']);
    //     $data['content'] = '客服将会在72小时内联系您，指派师傅上门安装';
    //     $status[] = $data;
    //     return $status;
    // }

    /**
     * 安装完成
     * @param  int $userId  用户ID
     * @param  int $orderId 订单ID
     * @return mixed          
     */
    public function finish($userId, $orderId)
    {
        $orderModel = M('WaterPurifierOrder');
        $map['user_id'] = $userId;
        $map['order_id'] = $orderId;
        $map['order_status'] = 1;
        $map['is_deleted'] = 0;
        $order = $orderModel->where($map)->find();
        if(!$order){
            $this->setError('20001', '订单不存在');
            return false;
        }
        if ($order['finish_time'] > 0) {
            $this->setError('20002', '订单已完成，无须重复操作');
            return false;
        }
        $data['finish_time'] = time();
        $data['finish_type'] = 1;
        $res = $orderModel->where($map)->save($data);
        return $res;
    }


    //获取用户订单列表
    public function getOrderList($userId, $orderType = 0)
    {
        // $map['config_key'] = 'cover_pic';
        // $pic = $this->where($map)->getField('url');
        // unset($map);
        if (!in_array($orderType, array(0, 1, 2, 3, 4))) {
            $this->setError(10001, '订单类型错误');
            return false;
        }
        $pic = '';
        $map['user_id'] = $userId;
        $map['is_deleted'] = 0;
        $map['pay_time'] = array('gt', 0);
        //$map['order_status'] = 1;
        if ($orderType > 0 and $orderType <= 3) {
            $map['order_type'] = $orderType;
        }elseif($orderType == 4){
            $map['order_type'] = array('elt', 2);
        }
        $model = M('WaterPurifierOrder');
        $order = $model->field('order_id,order_type,add_time,finish_time,cancel_time,actually_total')
               ->where($map)->order('add_time desc')->select();
        if (!$order) {
            return array('pic'=>$pic, 'order'=>array());
        }
        foreach ($order as $k => $v) {
            if($v['finish_time'] > 0){
                $order[$k]['title'] = '安装完成';
                $order[$k]['time'] = date('Y-m-d H:i:s', $v['finish_time']);
            }else{
                $order[$k]['title'] = '服务中';
                $order[$k]['time'] = date('Y-m-d H:i:s', $v['add_time']);
            }
            if($v['cancel_time'] > 0){
                $order[$k]['title'] = '已取消';
            }
            if($v['order_type'] == 1){
                $order[$k]['order_type_text'] = '领取';
                $order[$k]['content'] = '领取了净水器';
            }elseif($v['order_type'] == 2){
                $order[$k]['order_type_text'] = '更换';
                $order[$k]['content'] = '更换了净水器滤芯';
            }else{
                $order[$k]['order_type_text'] = '维修';
                $order[$k]['content'] = '对净水器进行了一次维修';
            }
        }
        return array('pic'=>$pic, 'order'=>$order);
    }

    /**
     * 检查用户是否有未完成的订单
     * @param  [type] $userId [description]
     * @return [type]         [description]
     */
    public function checkOrder($userId)
    {
        $map['user_id'] = $userId;
        $map['order_status'] = 1;
        $map['pay_time'] = array('gt', 0);
        $map['is_deleted'] = 0;

        $model = M('WaterPurifierOrder');
        $order = $model->where($map)->order('add_time desc')->find();
        if(!$order){
            $settingMap['config_key'] = 'receive_actually_price';
            $settingMap['is_deleted'] = 0;
            $setting = M("WaterPurifier")->where($settingMap)
                     ->field(array('config_value'=>'name','brand'))->order('brand asc')->select();

            foreach ($setting as $k => $v) {
                if($v['brand'] == 1){
                    $setting[$k]['pic'] = 'http://7xrcjk.com2.z0.glb.qiniucdn.com/20170213_58a19b72ce8ab.png';
                }elseif($v['brand'] == 2){
                    $setting[$k]['pic'] = 'http://7xrcjk.com2.z0.glb.qiniucdn.com/20170213_58a19bad84ab2.jpg';
                }else{
                    $setting[$k]['pic'] = 'http://7xrcjk.com2.z0.glb.qiniucdn.com/20170213_58a19bc63cd11.png';
                }    
            }
            return array('data'=>$setting,'type'=>'icon');
        }else{
            return array('data'=>$order, 'type'=>'order');
        }
        // elseif($order['finish_time'] > 0){
        //     return ;
        // }else{
        //     return $order['order_id'];
        // }
    }

    /**
     * 获取用户上次订单地址或默认地址
     * @param int $userId 用户ID
     * @param  bool $isReceive 是否领取了净水器
     * @return [type]            [description]
     */
    public function getLastAddress($userId, $isReceive)
    {
        if($isReceive){
            $map['user_id'] = $userId;
            $map['order_status'] = 1;
            $map['is_deleted'] = 0;
            $map['pay_time'] = array('gt', 0);
            $model = M('WaterPurifierOrder');
            $addressId = $model->where($map)->order('add_time desc')
                      ->getField('address_id');
            if ($addressId) {
                $addrMap['user_id'] = $userId;
                $addrMap['is_del'] = 0;
                $addrMap['id'] = $addressId;
                $address = M('Address')->where($addrMap)->find();
            }else{
                $address = false;

            }
        }else{
            //未领取，查找默认地址
            $map['user_id'] = $userId;
            $map['is_del'] = 0;
            $map['status'] = 1;
            $address = M('Address')->where($map)->find();
        }
        return $address;
    }
}
